package org.dragonnova.business.web;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.http.HttpSession;

import org.dragonnova.business.common.Constants;
import org.dragonnova.business.model.User;
import org.dragonnova.business.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.alibaba.fastjson.JSON;
import com.base.pub.util.Base64Util;

public class WebsocketEndPoint implements WebSocketHandler {
	@Autowired
	private TagService tagService;
	private Timer timer;

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		session.sendMessage(new TextMessage("WebSocket:connected OK!"));
	}

	@Override
	public void handleMessage(final WebSocketSession wss, WebSocketMessage<?> wsm) throws Exception {
		if (timer == null)timer = new Timer(false);
		final String receiveStr = wsm.getPayload().toString();
		HttpSession session = (HttpSession) wss.getAttributes().get("httpsession");
		final int userId = getUserId(session);
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				try {
					@SuppressWarnings("rawtypes")
					List  list =null;
					if (receiveStr.equals("tag")) {
						 list = tagService.findDeviceTag(userId, null, null,1);
					} else if (receiveStr.equals("box")) {
						 list = tagService.findDeviceBox(userId, null, null);
					}
					String json = JSON.toJSONString(list);
					wss.sendMessage(new TextMessage(json));
				} catch (Exception e) {
					try {
						wss.sendMessage(new TextMessage(e.getMessage()));
					} catch (IOException e1) {
						e1.printStackTrace();
					}
					e.printStackTrace();
				}
			}
		}, 0, 6000);
	}

	@Override
	public void handleTransportError(WebSocketSession wss, Throwable thrwbl) throws Exception {
		if (wss.isOpen()) {
			wss.close();
		}
		System.out.println("websocket connection closed......");
	}

	@Override
	public void afterConnectionClosed(WebSocketSession wss, CloseStatus cs) throws Exception {
		System.out.println("websocket connection closed......");
		timer.cancel();
		timer=null;
	}

	@Override
	public boolean supportsPartialMessages() {
		return false;
	}

	/**
	 * 管理员
	 */
	public int getUserId(HttpSession session) {
		if (session == null) {
			return -1;
		}
		User user =(User) session.getAttribute(Constants.LOGIN_KEY);
		if(user.getGid()==1){
			return -10;	
		}
		return  Integer.parseInt(Base64Util.getFromBase64(user.getId()));
	}

}
